//
//  EpointAttachViewController.m
//  EpointFrame5
//
//  Created by Pill Gong on 14-2-21.
//  Copyright (c) 2014年 Epoint. All rights reserved.
//

#import "EpointAttachViewController.h"
#import "AttachTableViewCell.h"
#import "UIView+Addtions.h"
#import "EpointAttachOpenViewController.h"
#import "SGAlertMenu.h"
#import "EpointAttachDownListTableViewCell.h"
#import "EpointAttachDownloadListViewController.h"
#import "UIAlertView+Blocks.h"


@interface EpointAttachViewController () <UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchDisplayDelegate>

@property (nonatomic, retain) NSMutableArray *dataArray;
@property (nonatomic, retain) UITableView *table;
@property (nonatomic, strong) NSMutableArray *resultDataArray;
@property (nonatomic, strong) NSMutableArray *allAttachArray;

@end

@implementation EpointAttachViewController {
    int selectedRow;
    UISearchDisplayController *searchController;
    UISearchBar *sb;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self addRightNavigationItem];
    
    self.resultDataArray = [[NSMutableArray alloc] initWithCapacity:5];
    [self addSearchBar];
    
    self.dataArray = [[NSMutableArray alloc] initWithCapacity:5];
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, NavigationBarHeight, AppWidth, AppHeight - SystemTakeHeight - NavigationBarHeight)];
    _table.delegate = self;
    _table.dataSource = self;
    [self setExtraCellLineHidden:_table];
    [self.view addSubview:_table];

    self.allAttachArray = [self.class getAllAttachArray];
    [self getData];
}

- (void)addRightNavigationItem {
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"清空" style:UIBarButtonItemStylePlain target:self action:@selector(clearAllPressed)];
    [self setRightBarButtonItemWithTitle:@"清空" action:@selector(clearAllPressed)];
}


- (void)clearAllPressed {
    
    RIButtonItem* cancelBtn = [RIButtonItem item];
    cancelBtn.label=@"取消";
    cancelBtn.action=^{};
    RIButtonItem* okBtn =[RIButtonItem item];
    okBtn.label=@"确定";
    okBtn.action=^{
        [self clearAll];
    };
    UIAlertView* delAlert =[[UIAlertView alloc] initWithTitle:@"提示" message:@"确定要清空所以附件吗？" cancelButtonItem:cancelBtn otherButtonItems:okBtn, nil];
    [delAlert show];
}

- (void)clearAll {
    
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentPath, @"attaches"];
    NSArray *subFile = [self getContentsArrAtPath:filePath];
    
    for (NSString *fileName in subFile) {
        [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", filePath, fileName] error:nil];
    }
    
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    if (_dataArray.count == 0) {
        return;
    }
    NSMutableArray *tempArray = [self getIndexPathsWithArrayCount:_dataArray.count-1 atIndexPath:indexPath];
    [tempArray insertObject:indexPath atIndex:0];
    [_dataArray removeAllObjects];
    [_table deleteRowsAtIndexPaths:tempArray withRowAnimation:UITableViewRowAnimationAutomatic];
    if (_resultDataArray) {
        [_resultDataArray removeAllObjects];
    }
    
    if (_allAttachArray) {
        [_allAttachArray removeAllObjects];
    }
}

- (void)addSearchBar {
    sb = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, AppWidth, NavigationBarHeight)];
    sb.placeholder = @"关键字检索";
    sb.delegate = self;
    [self.view addSubview:sb];
    
    searchController = [[UISearchDisplayController alloc]initWithSearchBar:sb contentsController:self];
    searchController.searchResultsTableView.backgroundColor = [UIColor clearColor];
    searchController.searchResultsTableView.separatorColor = [UIColor clearColor];
    searchController.delegate = self;
    searchController.searchResultsDataSource = self;
    searchController.searchResultsDelegate = self;
    searchController.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
    searchController.searchResultsTableView.bounces = NO;
    searchController.searchResultsTableView.tag = 2;
}

- (void)getData {
//    [_dataArray addObjectsFromArray:[self getData:@"attaches" withLevel:0]];
    [_dataArray addObjectsFromArray:_allAttachArray];
    [_table reloadData];
}

+ (NSMutableArray *)getAllAttachArray {

    NSMutableArray *tempAttachArray = [[NSMutableArray alloc] initWithCapacity:10];
    
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentPath, @"attaches"];
    
    NSArray *totalArr = [[NSFileManager defaultManager] subpathsAtPath:filePath];
    for (NSString *partPath in totalArr) {
        NSString *tempFilePath = [NSString stringWithFormat:@"%@/%@", filePath, partPath];
        BOOL isDirectory = NO;
        [[NSFileManager defaultManager] fileExistsAtPath:tempFilePath isDirectory:&isDirectory];
        if (isDirectory) {
            continue;
        }
        AttachInfo *info = [[AttachInfo alloc] init];
        info.fileName = [tempFilePath lastPathComponent];
        info.superFile = [tempFilePath stringByDeletingLastPathComponent];
        info.filePath = tempFilePath;
        [info fileIsDirectory];
        info.fileLevel = 0;
        [tempAttachArray addObject:info];
    }
    
    return tempAttachArray;
}

- (NSMutableArray *)getData:(NSString *)fileName withLevel:(int)level {

    NSString *filePath;
    if ([fileName isEqualToString:@"attaches"]) {
        NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        filePath = [NSString stringWithFormat:@"%@/%@", documentPath, fileName];
    } else {
        filePath = fileName;
    }

    NSArray *subFile = [self getContentsArrAtPath:filePath];
    NSMutableArray *tempArray = [[NSMutableArray alloc] initWithCapacity:subFile.count];
    for (NSString *subFileName in subFile) {
        AttachInfo *info = [[AttachInfo alloc] init];
        info.fileName = subFileName;
        info.superFile = fileName;
        info.filePath = [NSString stringWithFormat:@"%@/%@", filePath, subFileName];
        [info fileIsDirectory];
        info.fileLevel = level;
        [tempArray addObject:info];
    }
    return tempArray;
}

- (NSArray *)getContentsArrAtPath:(NSString *)filePath {
    NSArray *subFile = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:filePath error:nil];
    return subFile;
}

- (AttachInfo *)getAttachListData:(NSString *)fileName {
    AttachInfo *file = [AttachInfo.alloc init];
    file.fileName = fileName;

    if ([file fileIsDirectory] == NO) {
        return nil;
    }

    if (file.isDirectory) {
        NSError *error = nil;
        NSArray *subFileArr = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:file.filePath error:&error];
        if (error || subFileArr.count <= 0) {
            if (error) {
                NSLog(@"Error:%@", [error localizedDescription]);
            } else {
                NSLog(@"subFileArr has not item");
            }
        }
        
        for (NSString *subFileName in subFileArr) {
            
        }
    } else {
        return file;
    }
    return nil;
}

- (NSString *)getDocumentPath {
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSArray *array = [[NSFileManager defaultManager] subpathsAtPath:documentPath];
    return [array firstObject];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identifier = @"EpointAttachDownListTableViewCell";
    EpointAttachDownListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell==nil) {
        if (cell==nil) {
            NSString *nibName = @"EpointAttachDownListTableViewCell";
            if (CurrentDeviceISiPad) {
                nibName = @"EpointAttachDownListTableViewCell_pad";
            }
            NSArray *nib = [[NSBundle mainBundle]loadNibNamed:nibName owner:self options:nil];
            cell = [nib objectAtIndex:0];
        }
    }
    AttachInfo *info;
    if (tableView == _table) {
        info = [_dataArray objectAtIndex:indexPath.row];
    } else {
        info = [_resultDataArray objectAtIndex:indexPath.row];
    }
    
    cell.fileNameLabel.text = info.fileName;
    [cell.iconView setImage:[UIImage imageNamed:[EpointAttachDownloadListViewController getImageNameByFileName:info.fileName]]];
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == _table) {
        return _dataArray.count;
    } else {
        return _resultDataArray.count;
    }
}

- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {

    AttachInfo *info = [_dataArray objectAtIndex:indexPath.row];
    if (tableView == _table) {
        info = [_dataArray objectAtIndex:indexPath.row];
    }
    else {
        info = [_resultDataArray objectAtIndex:indexPath.row];
    }
    NSLog(@"info.filePath:%@", info.filePath);
    [[NSFileManager defaultManager] removeItemAtPath:info.filePath error:nil];

    NSMutableArray *indexPaths;
    if (info.isDirectory) {
        int count = [self removeCellsAtIndex:indexPath.row];
        indexPaths = [self getIndexPathsWithArrayCount:count
                                           atIndexPath:[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section]];
        [indexPaths insertObject:indexPath atIndex:0];
    } else {
        indexPaths = [[NSMutableArray alloc] initWithObjects:indexPath, nil];
        if (tableView == _table) {
            NSLog(@"info:%@", info.superFile);
            NSArray *array = [self getContentsArrAtPath:info.superFile];
            if (array.count == 0) {
                [self performSelector:@selector(updateDirectoryCellAccessoryView:) withObject:indexPath afterDelay:0.2];
            }
        }
    }
    if (tableView == _table) {
        [_dataArray removeObjectAtIndex:indexPath.row];
        if (indexPath.row == _dataArray.count && _table.contentSize.height < _table.height) {
            _table.size = CGSizeMake(_table.contentSize.width, _table.contentSize.height-45);
        }
    } else {
        AttachInfo *tempInfo = [_resultDataArray objectAtIndex:indexPath.row];
        [self deleteTheSameAttachInfo:tempInfo];
        [_resultDataArray removeObjectAtIndex:indexPath.row];
    }
    
    [tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationTop];
}

- (void)deleteTheSameAttachInfo:(AttachInfo *)tempInfo {
    int index = -1;
    for (AttachInfo *attachInfo in _dataArray) {
        index++;
        if (attachInfo.isDirectory) {
            continue;
        }
        if ([attachInfo.filePath isEqualToString:tempInfo.filePath]) {
            break;
        }
    }
    if (index != -1) {
        NSArray *array = [self getContentsArrAtPath:tempInfo.superFile];
        if (array.count == 0) {
            [self performSelector:@selector(updateDirectoryCellAccessoryView:) withObject:[NSIndexPath indexPathForRow:index inSection:0] afterDelay:0.2];
        }
        [_dataArray removeObjectAtIndex:index];
        [_table reloadData];
    }
}

- (void)updateTableViewHeight {
    _table.height = AppHeight - SystemTakeHeight - NavigationBarHeight;
}

- (void)updateDirectoryCellAccessoryView:(NSIndexPath *)indexPath {
//    NSIndexPath *directoryIndexPath = [NSIndexPath indexPathForRow:indexPath.row-1 inSection:indexPath.section];
//    AttachTableViewCell *cell = (AttachTableViewCell *)[_table cellForRowAtIndexPath:directoryIndexPath];
//    [cell setIsOpened:NO];
//    [self updateCellAccessoryView:cell];
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView*)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"didEndEditing");
    if (tableView == _table) {
        [self updateTableViewHeight];
    }
//    NSLog(@"table:%f", _table.height);
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"editingStyle:%d", indexPath.row);
    if (tableView == _table) {
        return UITableViewCellEditingStyleDelete;
    } else {
        return UITableViewCellEditingStyleNone;
    }
}

- (NSString *)tableView:(UITableView *)tableView
titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 45.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    NSLog(@"didselected:%d", indexPath.row);
//    NSLog(@"didselected:%d", indexPath.row);
    
    AttachInfo *info;
    if (tableView == _table) {
        info = [_dataArray objectAtIndex:indexPath.row];
    } else {
        info = [_resultDataArray objectAtIndex:indexPath.row];
    }
    
    [info fileIsDirectory];
    if (info.isDirectory == NO) {
        [self openAttachWithAttachInfo:info];
        return;
    }
    
    AttachTableViewCell *cell = (AttachTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    if (cell.isOpened == NO) {
        cell.isOpened = YES;
        NSMutableArray *tempArray = [self getData:info.filePath withLevel:info.fileLevel+1];
        NSMutableArray *indexPaths = [self getIndexPathsWithArrayCount:tempArray.count
                                                           atIndexPath:indexPath];
        [self insertCells:tempArray atIndex:indexPath.row];
        [_table insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
    } else {
        cell.isOpened = NO;
        int count = [self removeCellsAtIndex:indexPath.row];
        NSMutableArray *indexPaths = [self getIndexPathsWithArrayCount:count
                                                           atIndexPath:indexPath];
        [tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationTop];
    }
    [self updateCellAccessoryView:cell];

}

- (void)openAttachWithAttachInfo:(AttachInfo *)info {
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:info.fileName forKey:@"title"];
    NSString *folderGuid = [info.superFile lastPathComponent];    
    [params setObject:folderGuid forKey:@"folderguid"];
    EpointAttachOpenViewController *ao = [[EpointAttachOpenViewController alloc]init];
    ao.passParam = params;
    [self.navigationController pushViewController:ao animated:YES];
}

- (void)updateCellAccessoryView:(AttachTableViewCell *)cell {
    [UIView animateWithDuration:0.2 animations:^{
        if (cell.isOpened) {
            cell.accessoryView.transform = CGAffineTransformMakeRotation(M_PI);
        } else {
            cell.accessoryView.transform = CGAffineTransformMakeRotation(0);
        }
    } completion:^(BOOL finished) {
        //        NSLog(@"finish");
    }];
}

- (NSMutableArray *)getIndexPathsWithArrayCount:(int)count
                                    atIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *indexPaths = [[NSMutableArray alloc] initWithCapacity:count];
    for (int i=1; i<count+1; i++) {
        [indexPaths addObject:[NSIndexPath indexPathForRow:indexPath.row+i inSection:indexPath.section]];
    }
    return indexPaths;
}


- (void)insertCells:(NSArray *)array atIndex:(int)index {
    [_dataArray insertObjects:array atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(index+1, array.count)]];
}

- (int)removeCellsAtIndex:(int)index {
    NSMutableArray *tempArray = [NSMutableArray array];
    
    AttachInfo *currentInfo = [_dataArray objectAtIndex:index];
    int curLevel = currentInfo.fileLevel;
    
    for (int i=index+1; i<_dataArray.count; i++) {
        AttachInfo *tempInfo = [_dataArray objectAtIndex:i];
        if (tempInfo.fileLevel > curLevel) {
            [tempArray addObject:tempInfo];
        } else {
            break;
        }
    }
    
    if (tempArray.count > 0) {
        [_dataArray removeObjectsInArray:tempArray];
    }
    return tempArray.count;
}

- (void)setExtraCellLineHidden: (UITableView *)tableView
{
    UIView *view =[ [UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
}

#pragma mark - UISearchDisplayDelegate

-(void)searchDisplayController:(UISearchDisplayController *)controller willHideSearchResultsTableView:(UITableView *)tableView
{
    [_table setHidden:NO];
}

-(void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView
{
    [_table setHidden:YES];
}

#pragma mark - UISearchBarDelegate

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    //[_dataArray removeAllObjects];
    if (self.resultDataArray==nil) {
        self.resultDataArray = [NSMutableArray arrayWithCapacity:20];
    }
    [_resultDataArray removeAllObjects];
    
    [self findTheAttachContain:searchText];
    [searchController.searchResultsTableView reloadData];
    //    [self showMBPHUD];
    //    [self getData];
}

- (void)findTheAttachContain:(NSString *)searchText {
    
    for (AttachInfo *info in _allAttachArray) {
        if ([[info.fileName uppercaseString] rangeOfString:[searchText uppercaseString]].length > 0) {
            [_resultDataArray addObject:info];
        }
    }
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"searchBarSearchButtonClicked");
    [_dataArray removeAllObjects];
    [_dataArray addObjectsFromArray:_resultDataArray];
    [_table reloadData];
    [self resignSearchAction];
}

- (void)resignSearchAction {
    [sb resignFirstResponder];
    [searchController setActive:NO animated:YES];
}

@end
